#pragma once

#include "TcpServer.hpp"
#include "Log.hpp"
#include "Util.hpp"
#include "Task.hpp"
#include "ThreadPool.hpp"
#include <signal.h>

#define PORT 3389
class HttpServer
{
private:
    int _port;
public:
    HttpServer(int port = PORT)
        : _port(port)
    {
    }

    void InitServer()
    {
        signal(SIGPIPE,SIG_IGN);
    }
    void Loop()
    {
        LOG(INFO, "Loop begin");
        TcpServer *tsvr = TcpServer::GetInstance(_port);
        while (true)
        {
            struct sockaddr_in peer;
            socklen_t len = sizeof(peer);
            int sock = accept(tsvr->Sock(), (sockaddr *)&peer, &len);
            if (sock < 0)
                continue;

            std::string client_ip = inet_ntoa(peer.sin_addr);
            uint16_t client_port = ntohs(peer.sin_port);
            LOG(INFO, "get a new link:" + client_ip + " " + std::to_string(client_port));
            
            Task task(sock);
            ThreadPool::GetInstance()->PushTask(task);
        }
    }
    ~HttpServer()
    {}
};